var MESSAGE_HAPPY = {
    showMessageId: null,
    isBlockCabinet: false,
    isUploadedFile: 1,
    isUploadedVideo: 1,
    videoData: {},
    type: 1,
    btOpen: [],
    show: function(id_order) {
        alert(id_order);
        $('#mh_id_order').val(id_order);
        $('#message_happy').show();
        createUploader(document.getElementById('add_message_happy_filess'),
            function() {
                MESSAGE_HAPPY.isUploadedFile = 3;
            },
            function() {
                MESSAGE_HAPPY.isUploadedFile = 2;
            },
            ["jpg", "jpeg", "gif", "png"]);
        $('#message_happy').dialog({
            width: 800,
            height: 600,
            title: getTranslation('Message happy'),
            buttons: '#message_happy_buttons',
            modal: true,
            closed: false,
            onClose: function() {
                if (MESSAGE_HAPPY.isBlockCabinet) {
                    MESSAGE_HAPPY.show(id_order);
                }
            }
        });
        $('#message_happy .dialog-content').scroll(function() {
            MESSAGE_HAPPY.closeAllBt();
        });
    },
    getText: function(id_order) {
        $.ajax({
            url: '1701.npl',
            data: {
                a: 'gt',
                id_order: id_order,
            },
            success: function(data) {
                if (handleState(data)) {
                    if (data[42]) {
                        $('#message_happy_text').val(data[42].text);
                        $('#message_happy_videos').val(data[42].video);
                        $('#message_happy_comment').hide();
                        if (data[42].comment && data[42].comment != 'undefined' && data[42].comment != '') {
                            $('#message_happy_comment').show();
                            var comment_html = data[42].comment;
                            if (data[42].show_chat) comment_html += "<br><br><a class='translate' href='#' onclick='MESSAGE_HAPPY.openChatWindow(" + data[42].id + "); return false;'>" + getTranslation('Open chat') + "</a>";
                            $('#message_happy_comment div').html(comment_html);
                        }
                    }
                }
            }
        });
    },
    hide: function() {
        $('#message_happy').dialog('close');
    },
    latter: function() {
        location.reload();
        MESSAGE_HAPPY.hide();
    },
    showBt: function(p1, p2, p3) {

        $(p1).bt({
            trigger: 'none',
            contentSelector: "$('<div>" + getTranslation(p2).replace("'", "`") + "</div>')",
            width: p3,
            fill: 'red',
            positions: 'top',
            closeWhenOthersOpen: true,
            cssStyles: {
                color: 'white'
            }
        });
        $(p1).btOn();

        MESSAGE_HAPPY.btOpen.push(p1);
    },
    save: function() {
        var id_order = $('#mh_id_order').val();
        var text = $('#message_happy_texts').val();
        var video = $('#message_happy_videos').val();
        var want_5proc = $('#message_happy_want_5proc:checked')[0] ? 1 : 0;
        var pics ="";
        $("#message_happy_t input[name='pics']").each(function(){
            pics = pics+","+$(this).val();
        });
        if (text.length < 20) {
            $('#message_happy_texts').focus();
            setTimeout(function() {
                MESSAGE_HAPPY.showBt('#message_happy_texts', 'Too short text', 150);
            },200);
            return;
        }
        if (MESSAGE_HAPPY.isUploadedFile == 2) {
            setTimeout(function() {
                    MESSAGE_HAPPY.showBt('#add_message_happy_filess', 'wait_upload_file', 300)
                },
                200);
            return;
        }
        if (video == '') {
            var pattern = "^(([^:/\\?#]+):)?(//(([^:/\\?#]*)(?::([^/\\?#]*))?))?([^\\?#]*)(\\?([^#]*))?(#(.*))?$";
            var rx = new RegExp(pattern);
            var parts = rx.exec(video);
            var video_host = parts[4] || "";
            var is_youtube = video_host == 'youtube.com' || video_host == 'youtu.be' || video_host == 'www.youtube.com' || video_host == 'www.youtu.be';
            var is_link = parts[1] == 'http:' || parts[1] == 'https:'
            if (! (is_link && ((id_structure == 14 && !is_youtube) || (id_structure != 14 && is_youtube)))) {
                $('#message_happy_videos').focus();
                setTimeout(function() {
                        MESSAGE_HAPPY.showBt('#message_happy_videos', 'insert_video_youtube2', 400)
                    },
                    200);
                return;
            }


        } else {
            MESSAGE_HAPPY.sendSave(id_order,text,video,want_5proc,pics);
            var $par_=$("#message_happy_t").parents(".window");
            $(".panel-tool-close",$par_).click();
        }
    },
    sendSave: function(id_order, text, video, want_5proc,pics) {
        loadingShow();
        $.ajax({
            url: baselocation+'/my_messages_happy/write/',
            type: 'post',
            data: {
                type: $('#mh_type').val(),
                id_order: id_order,
                text: text,
                video: video,
                want_5proc: want_5proc,
                happymsgpics:pics
            },
            success: function(data) {
                if (data.code==1) {
                    loadingHide();
                    MESSAGE_HAPPY.hide();
                    loadArrangementsAndOrders()
//                    if (typeof window['loadOrders'] == 'function') {
//                        loadOrders();
//                    }
                } else {
                    alert('Error (102)');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert('Error (103)');
            }
        });
    },
    closeAllBt: function() {
        for (var i in MESSAGE_HAPPY.btOpen) {
            $(MESSAGE_HAPPY.btOpen[i]).btOff();
        }
        MESSAGE_HAPPY.btOpen = [];
    },
    getToDes: function() {
        $('#messages_happy').datagrid({
            fitColumns: true,
            nowrap: false,
            pagination: false,
            fit: true,
            pageSize: 30,
            idField: 'id',
            url: '1701.npl?a=gtd',
            columns: [[{
                field: 'username',
                title: getTranslation('Member'),
                width: 150,
                sortable: false
            },
                {
                    field: 'parentname',
                    title: getTranslation('position_10'),
                    width: 150,
                    sortable: false
                },
                {
                    field: 'text',
                    title: getTranslation('Message'),
                    width: 600,
                    formatter: function(value, row, index) {
                        return value ? value.nl2br() : '';
                    }
                },
                {
                    field: 'video',
                    title: getTranslation('Video'),
                    width: 200,
                    formatter: function(value, row, index) {
                        return value ? "<a href='" + value + "' target=_blank>" + value + "</a>": '';
                    }
                },
                {
                    field: 'files',
                    title: getTranslation('Files'),
                    width: 100,
                    formatter: function(value, row, index) {
                        var out = '';
                        if (value.length > 0) {
                            for (var i = 0; i < value.length; i++) {
                                out += "<a href=\"" + value[i] + "\" target=\"_blank\" class=\"_screens\"><img src='img/icons/jpg.png'></a> ";
                            }
                        }
                        return out;
                    }
                },
                {
                    field: 'crtime',
                    title: getTranslation('Date'),
                    width: 200,
                    sortable: true
                }]],
            onClickCell: function(rowIndex, field, value) {
                if (field == 'username' || field == 'parentname' || field == 'text') {
                    var rowData = $('#messages_happy').datagrid('getRows')[rowIndex];
                    MESSAGE_HAPPY.winChangeStatus(rowData);
                }
            }
        });
    },
    winChangeStatus: function(data) {
        $('#mh_info_text').html(data.text);
        $('#message_happy_info').show();
        $('#message_happy_info').dialog({
            width: 800,
            height: 440,
            title: getTranslation('Info'),
            buttons: '#message_happy_info_buttons'
        });
        MESSAGE_HAPPY.showMessageId = data.id;
    },
    winChangeStatusClose: function() {
        $('#message_happy_info').dialog('close');
        MESSAGE_HAPPY.showMessageId = null;
    },
    changeStatusDes: function(ident_status) {
        var comment = $('#message_happy_info_comment textarea').val();
        $.ajax({
            url: '1701.npl?a=csd&id=' + MESSAGE_HAPPY.showMessageId,
            data: {
                ident_status: ident_status,
                comment: comment
            },
            success: function(data) {
                if (!handleState(data)) {
                    return false;
                }
                $('#message_happy_info_comment textarea').val('');
                MESSAGE_HAPPY.showComment(false);
                MESSAGE_HAPPY.winChangeStatusClose();
                MESSAGE_HAPPY.getToDes();
            }
        });
    },
    showComment: function(show) {
        show ? $('#message_happy_info_comment').show() : $('#message_happy_info_comment').hide();
    },
    openChatWindow: function(id_message) {
        chatShowWindow(59, id_message,
            function() {});
    },
    blockForm: function(id_order) {
        MESSAGE_HAPPY.isBlockCabinet = true;
        $('#button_mh_write_later').hide();
    },
    setPereoform: function() {
        MESSAGE_HAPPY.type = 2;
        $('#deposit_pereoform').show();
        $('#deposit_amount').hide();
        $('#deposit_amount2').hide();
        $('#chain_letter1_order').hide();
        $('#chain_letter1_pereoform').show();
        $('$message_happy_want_5proc').parent().parent().hide();
    },
    showMessageKonkurs: function() {
        $("body").append("<div style=\"position:relative; margin:auto; width:740px;\"><div style=\"position:absolute; background:#BCDBFF; border:1px solid #BCDBFF; border-radius:10px; z-index:9100; top:220px; width:400px; right:0px; font-size:12px; padding:10px;\">Конкурс «Самое креативное ПС»<br><br>Условия участия:<br><br>Условие всего одно, окажите помощь от ста рублей и записывайте видео о получении помощи.<br>В видео можете читать стихи, вставлять интересные фотографии, петь, танцевать и так далее.<br><br>Каждую неделю мы будем выбирать три самых интересных и веселых письма счастья и объявлять победителей конкурса в Мавроновостях.<br>(Т.е. когда пишете видео для письма счастья, держите теперь в уме, что оно может на конкурсе победить. Поэтому − старайтесь! :-))<br><br>Победители получат в подарок Наличные Мавро.<br><br>1 место 300 долларов.<br>2 место 200 долларов.<br>3 место 100 долларов.<br><br><a href='http://3py4p4ods8eqivzcenynzr9rp7gt35bzg399i2tksesul6wmpyfe1nsawtno.com/news/37028-konkurs_samoe_kreativnoe_pismo_schastya.html' target=_blank>Подробнее</a><br><br>Участвуйте!<br>Побеждайте!<br><br>Мы Можем Многое!</div><img src='img/x.png' style=\"position:absolute; top:220px; right:0px; cursor:pointer; z-index:9101;\" onclick=\"$(this).parent().remove();\"></div>");
    }
};
